package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author xiongkunYang
 * @since 2025/05/26 18:30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    private final RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {
        return this.baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> productSkuList(SkuQuery skuQuery) {
        return this.baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = this.baseMapper.selectOne(queryWrapper);
        // 封装数据返回
        return SkuPriceVo.builder()
                .skuId(skuId)
                .salePrice(productSku.getSalePrice())
                .marketPrice(productSku.getMarketPrice())
                .build();
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        // 查询一个商品的所有sku
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getProductId, id)
                .select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkus = this.baseMapper.selectList(queryWrapper);
        // 封装数据返回
        return productSkus.stream().collect(Collectors.toMap(ProductSku::getSkuSpec, ProductSku::getId));
    }

    /**
     * 根据SkuID查询SKU商品信息
     *
     * @param skuId 商品SKU ID
     * @return SKU商品信息，如果找不到则返回空对象
     */
    @Override
    public ProductSku getProductSku(Long skuId) {

        //判断缓存中是否存在数据
        String dataKey = "product:sku:" + skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
        //如果存在则直接返回
        if (productSku != null) {
            log.info("命中缓存：{}", dataKey);
            return productSku;
        }

        //加分布式锁
        String lockKey = "product:sku:lock:" + skuId;
        String lockValue = UUID.randomUUID().toString().replace("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 3, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(flag)) {
            try {
                //再次查询缓存
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                //如果存在则直接返回
                if (productSku != null) {
                    log.info("命中缓存：{}", dataKey);
                    return productSku;
                }

                //如果不存在则从数据库中查询
                System.out.println("查询数据库");
                productSku = baseMapper.selectById(skuId);
                long ttl = 10;
                // 稻草人模式，解决缓存穿透
                if (productSku == null) {
                    //防止再次查询出来之后的值是null
                    productSku = new ProductSku();
                    ttl = 1;
                }

                //查询后将数据放入缓存
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.MINUTES);

                //返回数据
                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放分布式锁
                String script = """
                        if redis.call('get', KEYS[1]) == ARGV[1] then
                            return redis.call('del', KEYS[1])
                        else
                            return 0
                        end
                        """;
                Boolean result = redisTemplate.execute(
                        new DefaultRedisScript<>(script, Boolean.class),
                        List.of(lockKey),
                        lockValue
                );
                System.out.println("result = " + result);
            }
        } else {

            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //重试
            return getProductSku(skuId);
        }
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getId, skuIdList)
                .select(ProductSku::getId, ProductSku::getSalePrice);
        List<ProductSku> productSkus = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(productSkus)) {
            return productSkus.stream().map(productSku -> SkuPriceVo.builder()
                    .skuId(productSku.getId())
                    .salePrice(productSku.getSalePrice())
                    .build()).toList();
        }
        return List.of();
    }


}
